package com.util.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.List;


public class ExcelCellStyle extends AbstractCellStyleStrategy {

    @Override
    protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {

    }

    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {


        Workbook workbook = cell.getSheet().getWorkbook();

        try {
//            if (predicate.test(cell.getNumericCellValue())) {
                CellStyle cellStyle = getCellStyle(workbook);
                cell.setCellStyle(cellStyle);
//            }
        } catch (Exception e){}
    }
    CellStyle cellStyle;
    private CellStyle getCellStyle(Workbook workbook){
        if(cellStyle==null){
            cellStyle = workbook.createCellStyle();
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            cellStyle.setFillForegroundColor((IndexedColors.RED.index));
        }
        return cellStyle;
    }
//    获取cell的条件规则
    private static List<ConditionalFormattingRule> getConditionalRule(Sheet sheet, Cell cell){
        List<ConditionalFormattingRule> ruleList=new ArrayList<ConditionalFormattingRule>();
        if(cell!=null) {
            SheetConditionalFormatting scf=sheet.getSheetConditionalFormatting();//获取sheet中条件格式对象
            int countOfFormat=scf.getNumConditionalFormattings();//条件格式的数量
            for(int i=0;i<countOfFormat;i++) {
                ConditionalFormatting format=scf.getConditionalFormattingAt(i);//第countOfFormat个条件格式
                CellRangeAddress[] ranges=format.getFormattingRanges();//条件格式区域
                for(int r=0;r<ranges.length;r++) {
                    if(ranges[r].isInRange(cell)) {//cell是否在此区域
                        int numOfRule=format.getNumberOfRules();
                        for(int j=0;j<numOfRule;j++) {// 获取具体的规则
                            ConditionalFormattingRule rule=format.getRule(j);
                            ruleList.add(rule);
                        }

                    }
                }

            }
        }
        return ruleList;
    }
}
